<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入标题" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 193px">
          <el-option v-for="dict in forum_article_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['forum:article:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['forum:article:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['forum:article:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['forum:article:export']">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="atricleId" />
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容" align="center" prop="content" />
      <el-table-column label="简介" align="center" prop="introduction" />
      <el-table-column label="类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="forum_article_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['forum:article:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleSingleDelete(scope.row)"
            v-hasPermi="['forum:article:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改文章对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="articleRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option v-for="dict in forum_article_type" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <!-- 单项 -->
        <div v-if="form.type === 0">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="简介" prop="introduction">
            <el-input v-model="form.introduction" placeholder="请输入简介" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <editor v-model="form.content" :min-height="192" />
          </el-form-item>
          <el-form-item label="标签" prop="classId">
            <el-select v-model="form.classId" multiple multiple-limit="3" placeholder="请选择">
              <el-option v-for="item in articleTag" :key="item.classId" :label="item.className"
                :value="item.classId"></el-option>
            </el-select>
          </el-form-item>
        </div>
        <!-- 多项 -->
        <div v-if="form.type === 1">
          <el-form-item label="类目" prop="classId">
            <el-select v-model="form.classId" placeholder="请选择">
              <el-option v-for="item in classList" :key="item.classId" :label="item.className"
                :value="item.classId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="简介" prop="introduction">
            <el-input v-model="form.introduction" placeholder="请输入简介" />
          </el-form-item>
          <el-form-item label="数量" prop="num">
            <el-select v-model="form.num" clearable placeholder="请选择">
              <el-option v-for="item in 8" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-for="(items, index) in form.num" :key="index">
            <el-form-item :label="`关键词${items}`" :prop="`content.key${index}`">
              <el-input v-model="content[`key${index}`]" placeholder="请输入关键词" />
            </el-form-item>
            <el-form-item :label="`内容${items}`" :prop="`content.value${index}`" style="margin-top: 10px;">
              <el-input v-model="content[`value${index}`]" placeholder="请输入内容" />
            </el-form-item>
          </el-form-item>
          <el-form-item label="模板" prop="template">
            <el-input v-model="form.template" type="textarea" placeholder="请输入模板" />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Article">
import { listArticle, getArticle, delArticle, addArticle, updateArticle, getArticleTagAPI, delSingleArticle, getClassNameAPI } from "@/api/forum/article";
const { proxy } = getCurrentInstance();

const { forum_article_type } = proxy.useDict(
  "forum_article_type"
);



const articleList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const content = ref({})

const data = reactive({
  form: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    insertId: null,
    insertTime: null,
    updatePerson: null,
    deletePerson: null,
    deleteTime: null,
    title: null,
    content: null,
    type: null,
    classId: null
  },
  rules: {
    classId: [{ required: true, message: "标签不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询文章列表 */
function getList() {
  loading.value = true;
  listArticle(queryParams.value).then(response => {
    articleList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  content.value = {}
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    atricleId: null,
    insertId: null,
    insertTime: null,
    updatePerson: null,
    updateTime: null,
    deletePerson: null,
    deleteTime: null,
    title: null,
    content: null,
    type: null,
    classId: null
  };
  proxy.resetForm("articleRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.atricleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加文章";
  content.value = {}
}

// type===1的话 content反显
function transformToKeyValue(obj) {
  const result = {};
  let index = 0;
  for (const pair of obj) {
    const [key, value] = pair.split(":");
    result[`key${index}`] = key;
    result[`value${index}`] = value;
    index++;
  }
  return result;
}
/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _atricleId = row.atricleId || ids.value
  getArticle(_atricleId).then(response => {
    form.value = response.data;
    // 从forumAtricleClassVOList 提取clssId
    form.value.classId = Array.from(new Set(Object.values(form.value.forumAtricleClassVOList).map(item => item.classId)));
    if (form.value.type === 1) {
      form.value.classId = form.value.classId[0]
      content.value = JSON.parse(form.value.content)
      content.value = transformToKeyValue(content.value)
    }
    open.value = true;
    title.value = "修改文章";
  });
}

/** 提交按钮 */
function submitForm() {
  const keyValuePairs = ref([]);
  // content拼接
  if (data.form.type === 1) {
    for (const key in content.value) {
      if (key.startsWith('key')) {
        const valueKey = key.replace('key', 'value');
        const pairString = `${content.value[key]}:${content.value[valueKey]}`;
        keyValuePairs.value.push(pairString);
      }
    }
  }
  proxy.$refs["articleRef"].validate(valid => {
    if (valid) {
      // 判断content长度并切割
      if (data.form.type === 1) {
        if (keyValuePairs.value.length > form.value.num) {
          keyValuePairs.value.splice(form.value.num);
        }
        data.form.content = JSON.stringify(keyValuePairs.value);
      }
      // clssid 标签拼接
      let forumAtricleClassVOList = []
      if (form.value.type === 0) {
        forumAtricleClassVOList = form.value.classId.map(id => ({
          atricleId: form.value.atricleId !== null ? form.value.atricleId : null,
          classId: id
        }));
        form.value.classId = null
      }else{
        forumAtricleClassVOList.push({
          atricleId: form.value.atricleId !== null ? form.value.atricleId : null,
          classId: form.value.classId
        });
        form.value.classId = null
      }
      if (form.value.atricleId != null) {
        updateArticle({
          ...form.value,
          forumAtricleClassVOList
        }).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addArticle({
          ...form.value,
          forumAtricleClassVOList
        }).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _atricleIds = row.atricleId || ids.value;
  proxy.$modal.confirm('是否确认删除文章编号为"' + _atricleIds + '"的数据项？').then(function () {
    return delArticle(_atricleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

// 单删
function handleSingleDelete(row) {
  const _atricleIds = row.atricleId || ids.value;
  proxy.$modal.confirm('是否确认删除文章编号为"' + _atricleIds + '"的数据项？').then(function () {
    return delSingleArticle(_atricleIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('forum/article/export', {
    ...queryParams.value
  }, `article_${new Date().getTime()}.xlsx`)
}

// 获取文章标签
const articleTag = ref()
function getArticleTag() {
  getArticleTagAPI().then(res => {
    articleTag.value = res.data
  })
}

// 获取文章类目
const classList = ref()
function getClassList(){
  getClassNameAPI().then(res =>{
    classList.value = res.data
  })
}


getList();
getArticleTag()
getClassList()
</script>
